package com.bw.user.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.user.entity.vo.UserLoginVo;
import com.bw.user.util.OssUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bw.user.entity.HouseUserEntity;
import com.bw.user.service.HouseUserService;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户表

 *
 * @author Hao_YunKai
 * @email 2745578447@qq.com
 * @date 2022-03-23 11:40:46
 */
@RestController
@CrossOrigin
@RequestMapping("user/house-user")
public class HouseUserController {
    @Autowired
    private HouseUserService houseUserService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @SuppressWarnings("all")
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private HttpServletRequest request;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = houseUserService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userPhone}")
    public R info(@PathVariable("userPhone") Long userPhone){
		HouseUserEntity houseUser = houseUserService.getById(userPhone);

        return R.ok().put("houseUser", houseUser);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody HouseUserEntity houseUser){
		houseUserService.save(houseUser);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody HouseUserEntity houseUser){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    String userRedis = redisTemplate.opsForValue().get(cookie.getValue());
                    // 判断redis是否有值
                    if (userRedis != null) {
                        HouseUserEntity houseUserEntity = JSON.parseObject(userRedis, new TypeReference<HouseUserEntity>() {
                        });
                        houseUserEntity.setNickName(houseUser.getNickName());
                        houseUserEntity.setUserImg(houseUser.getUserImg());
                        houseUserService.updateById(houseUserEntity);
                        return R.ok();
                    }
                }
            }
        }

        return R.error("您的登录信息已过期");
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] userPhones){
		houseUserService.removeByIds(Arrays.asList(userPhones));

        return R.ok();
    }

    /**
     * 获取验证码
     */
    @GetMapping("sendMsg/{phone}")
    public R sendMsg(@PathVariable("phone")String phone) {
        if (houseUserService.getById(phone) != null) {
            // 异步发送验证码
            rabbitTemplate.convertAndSend("codeQueue",phone);
            return R.ok();
        } else {
            return R.error("您还未注册，请先注册再登录");
        }
    }

    /**
     * 用户登录
     */
    @RequestMapping("login")
    public R login(@RequestBody UserLoginVo userLoginVo) {
        if (userLoginVo.getLoginFlag() == 1) {
            // 密码登录
            HouseUserEntity userByName = houseUserService.getOne(new QueryWrapper<HouseUserEntity>().eq("user_name", userLoginVo.getUserName()));
            if (userByName != null && userByName.getUserPwd().equals(userLoginVo.getUserPwd())) {
                // 登录成功
                soo(userByName);
                return R.ok().put("user",userByName);
            } else {
                return R.error("用户名或密码错误");
            }
        } else {
            // 手机号登录
            HouseUserEntity userByPhone = houseUserService.getById(userLoginVo.getUserPhone());
            if (userByPhone == null) {
                return R.error("您的手机号未注册，请先注册再登录吧");
            } else {
                String code = redisTemplate.opsForValue().get(userLoginVo.getUserPhone());
                if (code != null) {
                    if (code.equals(userLoginVo.getCode())) {
                        // 登录成功
                        soo(userByPhone);
                        return R.ok().put("user",userByPhone);
                    } else {
                        return R.error("验证码有误");
                    }
                } else {
                    return R.error("验证码已过期，请重新发送验证码");
                }
            }
        }
     }

     /**
     * 单点登录
     */
    private void soo(HouseUserEntity userByName) {
        // 登录对象存redis
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(userByName), 30, TimeUnit.MINUTES);
        // uuid存cookie
        Cookie cookie = new Cookie("token", uuid);
        cookie.setPath("/");
        cookie.setMaxAge(30 * 60);
        // 将cookie响应给浏览器
        response.addCookie(cookie);
    }

    /**
     * oss图片上传
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file) {
        return ossUtils.uploadFile(file);
    }

    /**
     * 用户注册
     */
    @RequestMapping("/register")
    public R register(@RequestBody HouseUserEntity userEntity) {

            houseUserService.save(userEntity);
            return R.ok();

    }
}
